package com.gengzp.rpc.core.impl;

import com.gengzp.rpc.context.RpcRequestContextHolder;
import com.gengzp.rpc.core.RpcRequestIdentificationCoreFunc;
import com.gengzp.rpc.model.requestIdentification.RpcRequestIdentification;
import org.springframework.stereotype.Component;

/**
 * @ClassName RpcRequestIdentificationCoreFuncImpl
 * @Description rpc框架请求标识核心方法实现类
 * @Author gengzp
 * @Date 2025/8/22 16:23
 */
@Component
public class RpcRequestIdentificationCoreFuncImpl implements RpcRequestIdentificationCoreFunc {

    @Override
    public void saveRequestId(String requestId) {
        RpcRequestIdentification currentRequestIdentification = getCurrentRequestIdentification();
        currentRequestIdentification.setRequestId(requestId);
        RpcRequestContextHolder.setRequestIdentification(currentRequestIdentification);
    }

    @Override
    public void saveInitialRequestFlag(Boolean initialRequestFlag) {
        RpcRequestIdentification currentRequestIdentification = getCurrentRequestIdentification();
        currentRequestIdentification.setInitialRequestFlag(initialRequestFlag);
        RpcRequestContextHolder.setRequestIdentification(currentRequestIdentification);
    }

    @Override
    public void saveEnableRemoteTransactionFlag(Boolean enableRemoteTransactionFlag) {
        RpcRequestIdentification currentRequestIdentification = getCurrentRequestIdentification();
        // 如果已经被事务管理, 那么无需重复赋值, 防止被后续无事务的方法覆盖
        if (currentRequestIdentification.getEnableRemoteTransactionFlag() != null &&
                currentRequestIdentification.getEnableRemoteTransactionFlag()) {
            return;
        }
        currentRequestIdentification.setEnableRemoteTransactionFlag(enableRemoteTransactionFlag);
        RpcRequestContextHolder.setRequestIdentification(currentRequestIdentification);
    }

    /**
     * 或与当前的请求标识信息线程变量
     *
     * @return 当前请求标识信息
     */
    @Override
    public RpcRequestIdentification getCurrentRequestIdentification() {
        RpcRequestIdentification requestIdentification = RpcRequestContextHolder.getRequestIdentification();
        if (requestIdentification == null) {
            requestIdentification = new RpcRequestIdentification();
        }
        return requestIdentification;
    }

    @Override
    public void clearCurrentRequestIdentification() {
        RpcRequestContextHolder.clearRequestIdentification();
    }

}
